#include "StdAfx.h"
#include "CodeView.h"

#include "CodeViewManager.h"


BEGIN_MESSAGE_MAP(CCodeView, CMDIChildWnd)
	ON_WM_CREATE()
	ON_WM_SETFOCUS()
	ON_WM_SIZE()
	ON_WM_CLOSE()
	ON_COMMAND(ID_EDIT_UNDO, OnEditUndo)
	ON_UPDATE_COMMAND_UI(ID_EDIT_UNDO, OnUpdateEditUndo)
	ON_COMMAND(ID_EDIT_CUT, OnEditCut)
	ON_COMMAND(ID_EDIT_COPY, OnEditCopy)
	ON_COMMAND(ID_EDIT_PASTE, OnEditPaste)
END_MESSAGE_MAP()


CCodeView::CCodeView(CCodeViewManager &a_rManager) :
m_rManager(a_rManager)
{
	VERIFY(m_Menu.LoadMenu(IDR_CODEVIEW));
}


BOOL CCodeView::Create(const CStringA &strCode)
{
	SetHandles(m_Menu, NULL);
	if (!LoadFrame(
		IDR_CODEVIEW,
		WS_OVERLAPPEDWINDOW |
		WS_VISIBLE |
		WS_MAXIMIZE |
		WS_CLIPCHILDREN,
		NULL
		))
	{
		return FALSE;
	}

	::SetWindowTextA(m_ctrlEdit, strCode);
	return TRUE;
}

VOID CCodeView::SetCode(const CStringA *pCode)
{
	::SetWindowTextA(m_ctrlEdit, *pCode);
}


int CCodeView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	int nResult = CMDIChildWnd::OnCreate(lpCreateStruct);
	if (nResult != 0)
	{
		return nResult;
	}

	if (!m_ctrlEdit.Create(
		WS_CHILD |
		WS_VISIBLE |
		ES_MULTILINE |
		ES_READONLY |
		WS_VSCROLL |
		WS_HSCROLL,
		CRect(),
		this,
		1
		))
	{
		return -1;
	}

	if (!m_Font.CreateFont(
		12,
		0,
		0,
		0,
		0,
		FALSE,
		FALSE,
		FALSE,
		DEFAULT_CHARSET,
		OUT_DEFAULT_PRECIS,
		CLIP_DEFAULT_PRECIS,
		DEFAULT_QUALITY,
		DEFAULT_PITCH,
		_T("Courier")
		))
	{
		return -1;
	}

	m_ctrlEdit.SetFont(&m_Font);
	m_ctrlEdit.SetTabStops(16);

	return 0;
}

void CCodeView::OnSetFocus(CWnd *pOldWnd)
{
	CMDIChildWnd::OnSetFocus(pOldWnd);
	m_ctrlEdit.SetFocus();
}

void CCodeView::OnSize(UINT nType, int cx, int cy)
{
	m_ctrlEdit.MoveWindow(0, 0, cx, cy);
	CMDIChildWnd::OnSize(nType, cx, cy);
}

void CCodeView::OnClose()
{
	m_rManager.NotifyViewClosed();
	CMDIChildWnd::OnClose();
}


void CCodeView::OnEditUndo()
{
	m_ctrlEdit.Undo();
}

void CCodeView::OnUpdateEditUndo(CCmdUI *pCmdUI)
{
	pCmdUI->Enable(m_ctrlEdit.CanUndo());
}


void CCodeView::OnEditCut()
{
	m_ctrlEdit.Cut();
}

void CCodeView::OnEditCopy()
{
	m_ctrlEdit.Copy();
}

void CCodeView::OnEditPaste()
{
	m_ctrlEdit.Paste();
}
